package com.yq.homework.day29;

/**
 * @author 3307235355@qq.com
 * @description
 * @since 2022/06/29 14:44
 * (选做)启动3个线程打印递增的数字使用wait notifyAll
 * (稍微有点难,有困难的同学可以选做或看参考答案,理解了自己把答案盖住再写)
 * 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10,
 * 然后是线程3打印11,12,13,14,15.
 * 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75
 */
public class Demo02 {
    public static final Object OBJECT=new Object();
    static int a = 1;

    public static void main(String[] args) {
        new Thread(()->{
            while (a<=75){
                synchronized (OBJECT){
                    for (int i = 0; i < 5; i++) {
                        OBJECT.notifyAll();
                        System.out.println(Thread.currentThread().getName()+"===="+(a++));
                        if ((a-1)%5==0){
                            try {
                                OBJECT.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    OBJECT.notifyAll();
                }
            }
        },"t1").start();

        new Thread(()->{
            while (a<=75){
                synchronized (OBJECT){
                    for (int i = 0; i <5; i++) {
                        OBJECT.notifyAll();
                        System.out.println(Thread.currentThread().getName()+"===="+a++);
                        if ((a-1)%5==0){
                            try {
                                OBJECT.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                    OBJECT.notifyAll();
                }
            }
        },"t2").start();

        new Thread(()->{
            while (a<=75){
                synchronized (OBJECT){
                    for (int i = 0; i <5; i++) {
                        OBJECT.notifyAll();
                        System.out.println(Thread.currentThread().getName()+"===="+a++);
                        if ((a-1)%5==0){
                            try {
                                OBJECT.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                    OBJECT.notifyAll();
                }
            }
        },"t3").start();





    }
}
